package com.heima.media.tasks;

import com.alibaba.fastjson.JSON;
import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class MediaTasks {

    @Autowired
    private IAuditService auditService;

    @Autowired
    private RedissonClient redissonClient;

    @Async
    public void listen() throws InterruptedException {

        RBlockingQueue<String> queue = redissonClient.getBlockingQueue("publish-article");
        // 获取延迟队列
        RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(queue);
        // 初始化通道
        delayedQueue.offer("init", 1, TimeUnit.SECONDS);
        String poll = null;
        try {
            while (true) {
                // 接收消息,有消息,立刻执行消息的处理,没有消息,最多等待1分钟,
                poll = queue.poll(1, TimeUnit.MINUTES);
                if (poll != null && !poll.equals("init")) {
                    System.out.println("接收到消息为: " + poll + new Date());
                    WmNews wmNews = JSON.parseObject(poll, WmNews.class);
                    auditService.audit(wmNews);
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
